package com.zahb.qadx.ui.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseFragmentExt;
import com.zahb.qadx.model.CommonResponse;
import com.zahb.qadx.model.VideoListBean;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.skeleton.RecyclerViewSkeletonScreen;
import com.zahb.qadx.skeleton.Skeleton;
import com.zahb.qadx.ui.activity.VideoDetailsActivity;
import com.zahb.qadx.ui.adapter.VideoListAdapter;
import com.zahb.qadx.ui.view.decoration.MColorDrawable;
import com.zahb.qadx.ui.view.decoration.MDividerItemDecoration;
import com.zahb.qadx.util.CompatHelper;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.Tips;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * Created by Zdw on 2020/10/16 10:34
 * 精彩视频
 */
public class VideoListFragment extends BaseFragmentExt implements OnRefreshLoadMoreListener, OnItemClickListener {

    private boolean mIsFirstOnResume = true;

    private SmartRefreshLayout mRefreshLayout;

    private RecyclerView mRecyclerView;
    private VideoListAdapter mVideoListAdapter;

    private RecyclerViewSkeletonScreen mSkeletonScreen;
    private long mSkeletonShowTime;

    public static VideoListFragment newInstance(int position, String type) {
        Bundle args = new Bundle();
        args.putInt("position", position);
        args.putString("type", type);
        VideoListFragment fragment = new VideoListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mIsFirstOnResume) {
            //mRefreshLayout.autoRefresh();
            onRefresh(mRefreshLayout);
            showSkeleton();
            mIsFirstOnResume = false;
        }
    }

    @Override
    protected int getLayout() {
        return R.layout.fragment_video_list;
    }

    @Override
    protected void initViews(View rootView) {
        mRefreshLayout = rootView.findViewById(R.id.refresh_layout);
        mRefreshLayout.setOnRefreshLoadMoreListener(this);
        mRecyclerView = rootView.findViewById(R.id.recycler_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        MDividerItemDecoration itemDecoration = new MDividerItemDecoration(getContext());
        MColorDrawable colorDrawable = new MColorDrawable(CompatHelper.getColor(R.color.gray_999999));
        colorDrawable.setIntrinsicWidth(1).setIntrinsicHeight(1);
        itemDecoration.setDrawable(colorDrawable);
        itemDecoration.setShowLast(true);
        mRecyclerView.addItemDecoration(itemDecoration);
        mVideoListAdapter = new VideoListAdapter(R.layout.item_list_home_news);
        mVideoListAdapter.setOnItemClickListener(this);
        View emptyView = View.inflate(getContext(), R.layout.empty_layout, null);
        emptyView.setVisibility(View.VISIBLE);
        mVideoListAdapter.setEmptyView(emptyView);
        mRecyclerView.setAdapter(mVideoListAdapter);
    }

    private void showSkeleton() {
        mRefreshLayout.setEnableRefresh(false);
        mSkeletonScreen = Skeleton.bind(mRecyclerView)
                .adapter(mVideoListAdapter)
                .shimmer(true)
                .shimmerMode(RecyclerViewSkeletonScreen.SHIMMER_MODE_ITEM_CHILD)
                .angle(15)
                .frozen(true)
                //.color(R.color.black_333333)
                .duration(1000)
                .count(10)
                .load(R.layout.item_list_curriculum_skeleton)
                .show();
        mSkeletonShowTime = System.currentTimeMillis();
    }

    private void hideSkeleton() {
        if (mSkeletonScreen != null) {
            long currentTime = System.currentTimeMillis();
            if (currentTime - mSkeletonShowTime > Constant.MIN_NETWORK_TIME) {
                mRefreshLayout.setEnableRefresh(true);
                mSkeletonScreen.hide();
                mSkeletonScreen = null;
            } else {
                addDisposable(Observable.timer(mSkeletonShowTime + Constant.MIN_NETWORK_TIME - currentTime, TimeUnit.MILLISECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(aLong -> hideSkeleton()));
            }
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        refreshLayout.finishLoadMore(1000);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        refreshData(refreshLayout);
    }

    private void refreshData(RefreshLayout refreshLayout) {
        Observable<CommonResponse<ArrayList<VideoListBean>>> observable;
        String type = mArguments.getString("type");
        if (TextUtils.equals(type, "video"))
            observable = RetrofitService.getNetService().getGreatVideos();
        else if (TextUtils.equals(type, "audio"))
            observable = RetrofitService.getNetService().getGreatAudios();
        else
            return;
        addDisposable(observable.observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    refreshLayout.finishRefresh();
                    if (response.getStatusCode() == 200) {
                        mVideoListAdapter.setList(response.getData());
                    } else {
                        showBindToast(response.getErrorInfo());
                    }
                    hideSkeleton();
                }, throwable -> {
                    throwable.printStackTrace();
                    refreshLayout.finishRefresh();
                    Tips.RequestError(getActivity());
                    hideSkeleton();
                }));
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        String type = mArguments.getString("type");
        VideoDetailsActivity.actionStart(getContext(), mVideoListAdapter.getItem(position), type);
    }
}
